package priv.wjh.study.cloud.feign.api.config;

import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;
import org.springframework.util.CollectionUtils;
import priv.wjh.study.cloud.feign.api.JsonUtil;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;

/**
 * //TODO
 *
 * @author wangjunhao
 **/
public class MyDecoder implements Decoder {
    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
        Collection<String> generic = response.headers().get("generic");
        if (CollectionUtils.isEmpty(generic)) {
            if (type == String.class) {
                return bodyStr;
            }
            return JsonUtil.fromJson(bodyStr, type);
        }else {
            GenericWrapper genericWrapper = JsonUtil.fromJson(bodyStr, GenericWrapper.class);
            try {
                Class<?> clazz = Class.forName(genericWrapper.getClassName());
                return JsonUtil.fromJson(genericWrapper.getBody(), clazz);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
